package com.xdh.springcloud.security.jwt.auth.jwt;

import com.xdh.springcloud.security.jwt.common.auth.JwtAuthenticationToken;
import com.xdh.springcloud.security.jwt.common.factory.JwtTokenFactory;
import com.xdh.springcloud.security.jwt.common.model.UserModel;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class JwtAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private JwtTokenFactory jwtTokenFactory;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String token = (String) authentication.getCredentials();
        Jws<Claims> jwsClaims = jwtTokenFactory.parseClaims(token);
        Claims jwsClaimsBody = jwsClaims.getBody();

        UserModel userModel = new UserModel(jwsClaimsBody.getId(), jwsClaimsBody.getIssuer());
        List<GrantedAuthority> authorities = new ArrayList<>();
        return new JwtAuthenticationToken(userModel, authorities);
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return (JwtAuthenticationToken.class.isAssignableFrom(authentication));
    }
}
